package jmine.tec.web.wicket.component.button;

import static jmine.tec.web.wicket.spring.SpringBeanReference.forName;
import jmine.tec.web.wicket.BeanReference;
import jmine.tec.web.wicket.exception.ExceptionHandler;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.model.IModel;

/**
 * SubmitLink with exception handling support
 * 
 * @author lundberg
 */
public abstract class ActionSubmitLink extends SubmitLink {

    private BeanReference<ExceptionHandler> handler = forName("wicketExceptionHandler");

    /**
     * Constructor
     * 
     * @param id id
     * @param form form
     */
    public ActionSubmitLink(String id, Form<?> form) {
        super(id, form);
    }

    /**
     * Constructor
     * 
     * @param id id
     * @param model model
     * @param form form
     */
    public ActionSubmitLink(String id, IModel<?> model, Form<?> form) {
        super(id, model, form);
    }

    /**
     * Constructor
     * 
     * @param id id
     * @param model model
     */
    public ActionSubmitLink(String id, IModel<?> model) {
        super(id, model);
    }

    /**
     * Constructor
     * 
     * @param id id
     */
    public ActionSubmitLink(String id) {
        super(id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final void onSubmit() {
        try {
            this.onAction();
        } catch (Exception e) {
            this.handler.get().handle(e);
        }
    }

    /**
     * Action to be executed by the button on submit.
     * 
     * @throws Exception if anything wrong occurs
     */
    protected abstract void onAction() throws Exception;

}
